package com.mobi.cacti.ns.view;

import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.widget.ProgressBar;
import org.holoeverywhere.widget.TextView;

import com.mobi.cacti.R;
import com.mobi.cacti.rabbit.response.Cache;
import com.mobi.cacti.rabbit.response.GraphCircuit;
import com.mobi.cacti.rabbit.response.GraphType;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.webkit.SslErrorHandler;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.http.SslError;
import at.bookworm.widget.SegmentedControlButton;

public class GraphDetailActivity extends Fragment {

	private GraphCircuit graphCircuit;

	private TextView circuitIdTextView;

	private SegmentedControlButton totalRadioButton;
	private SegmentedControlButton interRadioButton;
	private SegmentedControlButton domesticRadioButton;

	private SegmentedControlButton dailyRadioButton;
	private SegmentedControlButton weeklyRadioButton;
	private SegmentedControlButton monthlyRadioButton;
	private SegmentedControlButton yearlyRadioButton;

	private RadioGroup graphTypeRadioGroup;
	private RadioGroup graphTimeRadioGroup;

	private WebView webView;
	private ProgressBar webViewProgressBar;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Bundle bundle = getArguments();
		graphCircuit = bundle.getParcelable("graphCircuit");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = LayoutInflater.from(getActivity()).inflate(
				R.layout.graphdetail_layout, null);

		circuitIdTextView = (TextView) v.findViewById(R.id.circuitid);
		circuitIdTextView.setText("CircuitID: " + graphCircuit.CircuitID);

		totalRadioButton = (SegmentedControlButton) v
				.findViewById(R.id.radio_total);
		interRadioButton = (SegmentedControlButton) v
				.findViewById(R.id.radio_inter);
		domesticRadioButton = (SegmentedControlButton) v
				.findViewById(R.id.radio_domestic);

		dailyRadioButton = (SegmentedControlButton) v
				.findViewById(R.id.radio_daily);
		weeklyRadioButton = (SegmentedControlButton) v
				.findViewById(R.id.radio_weekly);
		monthlyRadioButton = (SegmentedControlButton) v
				.findViewById(R.id.radio_monthly);
		yearlyRadioButton = (SegmentedControlButton) v
				.findViewById(R.id.radio_yearly);

		graphTypeRadioGroup = (RadioGroup) v
				.findViewById(R.id.graphtyperadiogroup);
		graphTimeRadioGroup = (RadioGroup) v.findViewById(R.id.graphtimegroup);

		webViewProgressBar = (ProgressBar) v
				.findViewById(R.id.webviewprogressbar);

		webView = (WebView) v.findViewById(R.id.graphwebview);
		setupWebView();

		if (!graphCircuit.isTotalGraphExist()) {
			totalRadioButton.setVisibility(View.GONE);
		} else {
			totalRadioButton.setVisibility(View.VISIBLE);
		}

		if (!graphCircuit.isInterGraphExist()) {
			interRadioButton.setVisibility(View.GONE);
		} else {
			interRadioButton.setVisibility(View.VISIBLE);
		}

		if (!graphCircuit.isDomesticGraphExist()) {
			domesticRadioButton.setVisibility(View.GONE);
		} else {
			domesticRadioButton.setVisibility(View.VISIBLE);
		}

		if (graphCircuit.isTotalGraphExist()
				&& graphCircuit.isInterGraphExist()
				&& graphCircuit.isDomesticGraphExist()) {
			totalRadioButton
					.setBackgroundResource(R.drawable.segmentedcontrol_left_selector_light_gray);
			interRadioButton
					.setBackgroundResource(R.drawable.segmentedcontrol_center_selector_light_gray);
			domesticRadioButton
					.setBackgroundResource(R.drawable.segmentedcontrol_right_selector_light_gray);

			totalRadioButton.setChecked(true);

		} else if (graphCircuit.isTotalGraphExist()
				&& graphCircuit.isInterGraphExist()
				&& !graphCircuit.isDomesticGraphExist()) {
			totalRadioButton
					.setBackgroundResource(R.drawable.segmentedcontrol_left_selector_light_gray);
			interRadioButton
					.setBackgroundResource(R.drawable.segmentedcontrol_right_selector_light_gray);

			totalRadioButton.setChecked(true);

		} else if (graphCircuit.isTotalGraphExist()
				&& !graphCircuit.isInterGraphExist()
				&& graphCircuit.isDomesticGraphExist()) {
			totalRadioButton
					.setBackgroundResource(R.drawable.segmentedcontrol_left_selector_light_gray);
			domesticRadioButton
					.setBackgroundResource(R.drawable.segmentedcontrol_right_selector_light_gray);

			totalRadioButton.setChecked(true);

		} else if (!graphCircuit.isTotalGraphExist()
				&& graphCircuit.isInterGraphExist()
				&& graphCircuit.isDomesticGraphExist()) {
			interRadioButton
					.setBackgroundResource(R.drawable.segmentedcontrol_left_selector_light_gray);
			domesticRadioButton
					.setBackgroundResource(R.drawable.segmentedcontrol_right_selector_light_gray);

			interRadioButton.setChecked(true);

		} else if (graphCircuit.isTotalGraphExist()
				&& !graphCircuit.isInterGraphExist()
				&& !graphCircuit.isDomesticGraphExist()) {
			totalRadioButton
					.setBackgroundResource(R.drawable.segmentedcontrol_selector_light_gray);

			totalRadioButton.setChecked(true);

		} else if (!graphCircuit.isTotalGraphExist()
				&& graphCircuit.isInterGraphExist()
				&& !graphCircuit.isDomesticGraphExist()) {
			interRadioButton
					.setBackgroundResource(R.drawable.segmentedcontrol_selector_light_gray);

			interRadioButton.setChecked(true);

		} else if (!graphCircuit.isTotalGraphExist()
				&& !graphCircuit.isInterGraphExist()
				&& graphCircuit.isDomesticGraphExist()) {
			domesticRadioButton
					.setBackgroundResource(R.drawable.segmentedcontrol_selector_light_gray);

			domesticRadioButton.setChecked(true);
		}

		totalRadioButton.setOnClickListener(radioButtonOnClickListener);
		interRadioButton.setOnClickListener(radioButtonOnClickListener);
		domesticRadioButton.setOnClickListener(radioButtonOnClickListener);

		dailyRadioButton.setOnClickListener(radioButtonOnClickListener);
		weeklyRadioButton.setOnClickListener(radioButtonOnClickListener);
		monthlyRadioButton.setOnClickListener(radioButtonOnClickListener);
		yearlyRadioButton.setOnClickListener(radioButtonOnClickListener);

		// restore
		if (Cache.graphDetailStateBundle != null) {
			int graphTypeRadioButtonID = Cache.graphDetailStateBundle
					.getInt("graphTypeRadioButtonID", 0);
			int graphTimeRadioButtonID = Cache.graphDetailStateBundle
					.getInt("graphTimeRadioButtonID", 0);

			if (graphTypeRadioButtonID != 0) {
				graphTypeRadioGroup.check(graphTypeRadioButtonID);
			}
			
			if (graphTimeRadioButtonID != 0) {
				graphTimeRadioGroup.check(graphTimeRadioButtonID);
			}
			
		}

		// check internet connection
		if (!Cache.isNetworkAvailable(getSupportActivity())) {
			// display alert dialog
			Cache.showNoInternetAlertDialog(getSupportActivity());
		}

		checkRadioButton();

		checkOrientation();

		return v;
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		if (graphTypeRadioGroup == null || graphTimeRadioGroup == null) {
			return;
		}

		int graphTypeRadioButtonID = graphTypeRadioGroup
				.getCheckedRadioButtonId();
		int graphTimeRadioButtonID = graphTimeRadioGroup
				.getCheckedRadioButtonId();

		// put selected items into cache
		Cache.graphDetailStateBundle.putInt("graphTypeRadioButtonID",
				graphTypeRadioButtonID);
		Cache.graphDetailStateBundle.putInt("graphTimeRadioButtonID",
				graphTimeRadioButtonID);
	}

	private void setupWebView() {
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setLoadWithOverviewMode(true);
		webView.getSettings().setUseWideViewPort(true);
		webView.getSettings().setBuiltInZoomControls(true);

		webView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);

				webViewProgressBar.setVisibility(View.VISIBLE);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);

				webViewProgressBar.setVisibility(View.GONE);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);

			}

			@Override
			public void onReceivedSslError(WebView view,
					SslErrorHandler handler, SslError error) {
				handler.proceed(); // Ignore SSL certificate errors
			}
		});
	}

	private void checkOrientation() {

		if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			// Set web view full screen when landscape
			circuitIdTextView.setVisibility(View.GONE);
			graphTypeRadioGroup.setVisibility(View.GONE);
			graphTimeRadioGroup.setVisibility(View.GONE);

			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT);

			webView.setLayoutParams(params);

		} else {
			// Restore web view size
			circuitIdTextView.setVisibility(View.VISIBLE);
			graphTypeRadioGroup.setVisibility(View.VISIBLE);
			graphTimeRadioGroup.setVisibility(View.VISIBLE);

			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT);

			params.addRule(RelativeLayout.ABOVE, R.id.graphtimegroup);
			params.addRule(RelativeLayout.BELOW, R.id.graphtyperadiogroup);

			webView.setLayoutParams(params);
		}
	}

	private void checkRadioButton() {
		int graphTypeRadioButtonID = graphTypeRadioGroup
				.getCheckedRadioButtonId();
		int graphTimeRadioButtonID = graphTimeRadioGroup
				.getCheckedRadioButtonId();

		GraphType graphType = null;

		if (graphTimeRadioButtonID == dailyRadioButton.getId()) {
			graphType = GraphType.DAILY;
		} else if (graphTimeRadioButtonID == weeklyRadioButton.getId()) {
			graphType = GraphType.WEEKLY;
		} else if (graphTimeRadioButtonID == monthlyRadioButton.getId()) {
			graphType = GraphType.MONTHLY;
		} else if (graphTimeRadioButtonID == yearlyRadioButton.getId()) {
			graphType = GraphType.YEARLY;
		}

		String imageUrl = null;

		if (graphTypeRadioButtonID == totalRadioButton.getId()) {
			imageUrl = graphCircuit.getTotalGraph(graphType);
		} else if (graphTypeRadioButtonID == interRadioButton.getId()) {
			imageUrl = graphCircuit.getInterGraph(graphType);
		} else if (graphTypeRadioButtonID == domesticRadioButton.getId()) {
			imageUrl = graphCircuit.getDomesticGraph(graphType);
		}
		
		if (Cache.graphDetailStateBundle == null) {
			Cache.graphDetailStateBundle = new Bundle();
		}

		// put selected items into cache
		Cache.graphDetailStateBundle.putInt("graphTypeRadioButtonID",
				graphTypeRadioButtonID);
		Cache.graphDetailStateBundle.putInt("graphTimeRadioButtonID",
				graphTimeRadioButtonID);

		reloadWebView(imageUrl);
	}

	private void reloadWebView(String imageUrl) {
		String customHtml = "<html><head>";
		customHtml += "<style>";
		customHtml += "img {";
		customHtml += "background: url('" + imageUrl
				+ "') center center no-repeat;";
		customHtml += "width: 100%;";
		customHtml += "height: auto;";
		customHtml += "background-size: contain;";
		customHtml += "}";

		customHtml += "html, body, #wrapper{";
		customHtml += "height:100%;";
		customHtml += "width: 100%;";
		customHtml += "margin: 0;";
		customHtml += "padding: 0;";
		customHtml += "border";
		customHtml += "}";

		customHtml += "#wrapper td{";
		customHtml += "vertical-align: middle;";
		customHtml += "text-align: center;";
		customHtml += "}";

		customHtml += "</style>";
		customHtml += "</head>";
		customHtml += "<body>";
		customHtml += "<table id=\"wrapper\"><td>";
		customHtml += "<img src=\"" + imageUrl + "\" />";
		customHtml += "</td></table>";
		customHtml += "</body>";
		customHtml += "</html>";

		webView.loadData(customHtml, "text/html", "UTF-8");
	}

	OnClickListener radioButtonOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			checkRadioButton();

		}
	};
}
